<template>
   <!-- 弹窗组件 -->
   <div class="dialog-box">
      <el-dialog
         v-model="dialogVisible"
         :title="flags === 1 ? '选择退货负责人' : '选择采购负责人'"
         width="800"
      >
         <div class="dialog-content">
            <!-- 分组区域保持不变 -->
            <div class="row-1">
               <div
                  class="row-1-title"
                  v-show="!is_search"
               >
                  <div>组织架构</div>
                  <div
                     style="cursor: pointer"
                     @click="handleSearch"
                  >
                     <el-icon><Search /></el-icon>
                  </div>
               </div>
               <div
                  class="row-1-title"
                  v-show="is_search"
               >
                  <el-input
                     style="width: 100%"
                     v-model="textValue"
                     placeholder="请输入"
                     placeholder-class="input-placeholder"
                     ref="SerRef"
                  />
               </div>
               <div class="row-1-content">
                  <el-tree
                     ref="treeRef"
                     style="max-width: 600px"
                     class="filter-tree"
                     node-key="id"
                     :accordion="true"
                     :data="Array.isArray(datas) ? datas : []"
                     :props="defaultProps"
                     :filter-node-method="filterNode"
                     @node-click="handleNodeClick"
                  />
               </div>
            </div>

            <!-- 左侧产品列表 -->
            <div class="row-2">
               <div class="table-container">
                  <el-table
                     ref="leftTableRef"
                     :data="tableData"
                     style="width: 100%"
                     border
                     :row-key="(row:User) => row.id"
                  >
                     <el-table-column width="55">
                        <template #default="scope">
                           <el-radio
                              v-model="selectedRowId"
                              :label="scope.row.id"
                              @change="handleRadioChange(scope.row)"
                           />
                        </template>
                     </el-table-column>
                     <el-table-column
                        label="姓名"
                        prop="name"
                        width="100"
                     >
                     </el-table-column>
                     <el-table-column
                        prop="id"
                        label="编号"
                        width="120"
                     />
                     <el-table-column
                        prop="org_position.position_name"
                        label="角色"
                        show-overflow-tooltip
                        width="120"
                     />
                     <el-table-column
                        prop="mobile"
                        label="联系电话"
                        show-overflow-tooltip
                        width="120"
                     />
                  </el-table>
               </div>
            </div>
         </div>

         <template #footer>
            <div class="dialog-footer">
               <el-button @click="dialogVisible = false">取消</el-button>
               <el-button
                  color="#626aef"
                  @click="submit"
                  >确认</el-button
               >
            </div>
         </template>
      </el-dialog>
   </div>
</template>

<script setup lang="ts">
   import { ref, defineEmits } from "vue";
   import { Search } from "@element-plus/icons-vue";
   import type { ElTable } from "element-plus";
   import api from "@/api/index.js";
   const flags = ref<number>();
   interface User {
      Sname: string;
      name: string;
      Sphone: string;
      Sposition: string;
      id: number;
   }
   interface Tree {
      label: string;
      children?: Tree[];
   }

   const handleNodeClick = (data: Tree) => {
      // 由于 Tree 类型没有 id 属性,需要扩展 Tree 接口
      org_id.value = (data as Tree & { id: number }).id;
      getOrganizationUser();
   };

   const datas = ref<Tree[]>([]);
   // 获取组织架构
   const getOrganization = async () => {
      const res = await api.authority.getOrgList();

      if (res.code === 200) {
         datas.value = res.data;
      }
   };
   const tableData = ref<User[]>([]);
   const org_id = ref<number>(0);
   // 获取组织人员
   const getOrganizationUser = async () => {
      const res = await api.authority.getPersonnelList({
         org_id: org_id.value || (datas.value[0] as Tree & { id: number }).id,
      });
      if (res.code === 200) {
         tableData.value = res.data.data;
      }
   };

   const selectedRowId = ref<Number>(); // 选中的行id
   const selectedRow = ref<User>(); // 选中的行

   const handleRadioChange = (row: User) => {
      is_search.value = false;
      selectedRow.value = row;
   };
   // 打开弹窗
   const dialogVisible = ref<boolean>(false);
   const openLoading = async (flag: number) => {
      await getOrganization(); // 获取组织架构
      org_id.value = (datas.value[0] as Tree & { id: number }).id;
      await getOrganizationUser(); // 获取组织人员
      dialogVisible.value = true;
      if (flag === 1) {
         flags.value = 1;
      }
   };
   const submit = () => {
      if (selectedRow.value) {
         emit("selectPurchasingDirector", selectedRow.value);
      }
      dialogVisible.value = false;
   };

   const emit = defineEmits(["selectPurchasingDirector"]);
   // 搜索
   import { ElInput, TreeInstance } from "element-plus";
   import { watch } from "vue";
   const textValue = ref<string>("");
   const is_search = ref<boolean>(false);
   const SerRef = ref<InstanceType<typeof ElInput>>();
   const handleSearch = () => {
      is_search.value = !is_search.value;
   };
   // 监听is_search变化，当为true时自动获取焦点
   watch(is_search, (newVal) => {
      if (newVal) {
         nextTick(() => {
            SerRef.value?.focus();
         });
      }
   });
   const treeRef = ref<TreeInstance>();

   const defaultProps = {
      children: "children",
      label: "name",
   };

   const filterNode = (value: string, data: Tree) => {
      if (!value) return true;
      return data.label.includes(value);
   };
   watch(textValue, (val) => {
      treeRef.value!.filter(val);
      // 当搜索框清空时，重置树的展开状态
      if (!val) {
         nextTick(() => {
            // 通过重新设置数据来重置树的状态
            const tempData = [...datas.value];
            datas.value = [];
            nextTick(() => {
               datas.value = tempData;
            });
         });
      }
   });
   defineExpose({ openLoading });
</script>

<style lang="scss" scoped>
   .dialog-content {
      display: flex;
      min-height: 400px;
      height: auto;
      transition: height 0.3s ease-in-out;
      flex-direction: row;
      gap: 10px;
      .row-1 {
         flex: 1;
         border: 1px solid #f0f0f0;

         .row-1-title {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 16px;
            width: 76%;
            height: 32px;
            border-bottom: 1px solid #f0f0f0;
            margin: 0 auto;
            color: #172b4d;
         }
         .row-1-content {
            padding: 10px;
            // padding-left: 20px;
            margin: 0 10px;
            // &:hover {
            //    background: #edecff;
            //    cursor: pointer;
            //    color: #626aef;
            // }
         }
      }
      .row-2 {
         flex: 2;
         border: 1px solid #f0f0f0;
         width: 100%;
         display: flex;
         flex-direction: column;
         overflow: hidden;

         .row-2-search {
            padding: 10px;
            width: 50%;
         }

         .table-container {
            flex: 1;
            overflow-y: auto;
            overflow-x: hidden;

            &::-webkit-scrollbar {
               width: 6px;
               height: 6px;
            }

            &::-webkit-scrollbar-thumb {
               border-radius: 3px;
               background: #ddd;
            }

            &::-webkit-scrollbar-track {
               border-radius: 3px;
               background: #f5f5f5;
            }

            .el-table {
               height: 100%;
            }
         }
      }
   }
   ::v-deep .el-dialog {
      --el-dialog-padding-primary: 0px;
   }
   ::v-deep .el-dialog__header {
      padding: 10px 16px;
      border-bottom: 1px solid #f0f0f0;
      font-weight: bold;
   }
   ::v-deep .dialog-footer {
      padding: 10px 16px;
      border-top: 1px solid #f0f0f0;
   }
   ::v-deep .el-dialog__headerbtn .el-dialog__close {
      color: #000;
   }
   ::v-deep .el-dialog__body {
      padding: 20px 10px;
   }
   :deep(.cell) {
      white-space: nowrap;
      text-overflow: ellipsis;
   }
   :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
      background-color: #6860ff;
      border-color: #6860ff;
   }
   :deep(.el-checkbox__inner:hover) {
      border-color: #626aef !important;
   }
   :deep(.el-checkbox__input.is-indeterminate .el-checkbox__inner) {
      background-color: #6860ff;
   }
   :deep(.el-checkbox__input.is-indeterminate .el-checkbox__inner) {
      border-color: #6860ff;
   }
   :deep(.el-radio__label) {
      display: none;
   }
   :deep(.el-radio__input.is-checked .el-radio__inner) {
      background: #6860ff;
      color: #6860ff;
   }
   :deep(.el-radio) {
      border-color: none;
   }
   :deep(.el-tree-node:focus > .el-tree-node__content) {
      background-color: #edecff;
   }
   :deep(.el-tree-node__content) {
      height: 36px;
   }
   :deep(.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content) {
      background-color: #edecff;
      color: #6860ff;
   }
   :deep(.el-radio__inner:hover) {
      border-color: #626aef;
   }
</style>
